/*
 * Created by IntelliJ IDEA.
 * User: amrk
 * Date: 10/06/2004
 * Time: 20:52:56
 */
package com.talios.jira.browser;

import com.intellij.openapi.diagnostic.Logger;
import com.talios.jira.JiraException;
import com.talios.jira.rpc.JiraRpcClient;

import javax.swing.*;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

public class IssueTypesComboBoxModel extends DefaultComboBoxModel {
    private static final Logger LOGGER = Logger.getInstance("Jira Browser");
    private List list = new ArrayList();

    public List getList() {
        return list;
    }

    public IssueTypesComboBoxModel(JiraRpcClient rpcClient) {

        try {
            list = rpcClient.getIssueTypes();
        } catch (JiraException e) {
            LOGGER.error("Unable to get Issue Types for Project: " + e.getMessage(), e);
        }
    }

    // implements javax.swing.ListModel
    public int getSize() {
        return list == null ? 0 : list.size();
    }

    // implements javax.swing.ListModel
    public Object getElementAt(int index) {
        Hashtable project = (Hashtable) list.get(index);
        if (project != null) {
            return project.get("name");
        } else {
            return "";
        }
    }

    public int getIndexOfId(Object anObject) {
        String projectId = (String) anObject;

        int index = 0;
        for (Object aList : list) {
            Hashtable hashtable = (Hashtable) aList;
            if (projectId.equals(hashtable.get("id"))) {
                return index;
            }

            index++;
        }

        return -1;
    }

    public int getIndexOfName(Object anObject) {
        String projectName = (String) anObject;

        int index = 0;
        for (Object aList : list) {
            Hashtable hashtable = (Hashtable) aList;
            if (projectName.equals(hashtable.get("name"))) {
                return index;
            }

            index++;
        }

        return -1;
    }

    public String getIdOfName(Object selectedItem) {
        int index = getIndexOfName(selectedItem);
        Hashtable hashtable = (Hashtable) list.get(index);
        return (String) hashtable.get("id");
    }

    public String getIdOfSelectedItem() {
        return getIdOfName(getSelectedItem());
    }

}